<template>
  <header class="edito-title">
    <div class="left-box"></div>
    <input
      class="title-input"
      spellcheck="false"
      maxlength="80"
      @input="handleTitle"
      v-model="form.title"
      type="text"
      placeholder="输入文章标题..."
    />
    <div class="rigth-box">
      <div class="status-text with-margin">{{ statusText }}</div>
      <el-button color="#1D7DFA" class="with-margin" plain>草稿箱</el-button>
      <div class="publish-popup with-margin">
        <el-button color="#1D7DFA" @click="publish">发布</el-button>
        <div class="panel" v-if="panelVisibleValue">
          <div class="from-title">发布文章</div>
          <el-form ref="formRef" :model="form" :rules="rules" class="publish-ruleForm" status-icon>
            <el-form-item label="分类" :label-width="formLabelWidth" prop="article_type">
              <el-radio-group v-model="form.article_type" size="small">
                <el-radio-button label="后端" />
                <el-radio-button label="前端" />
                <el-radio-button label="Android" />
                <el-radio-button label="iOS" />
                <el-radio-button label="人工智能" />
                <el-radio-button label="开发工具" />
                <el-radio-button label="代码人生" />
                <el-radio-button label="阅读" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="添加标签" :label-width="formLabelWidth" prop="tags_name">
              <el-select
                v-model="form.tags_name"
                multiple
                filterable
                allow-create
                :reserve-keyword="false"
                :multiple-limit="3"
                placeholder="请搜索添加标签"
              >
                <el-option
                  v-for="(item, index) in lableOptions"
                  :key="index"
                  :label="item.lableTitle"
                  :value="item.lableId"
                  :value-key="item.lableId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="文章封面" :label-width="formLabelWidth">
              <template #default>
                <el-upload
                  :class="{ hide: hideUploadEdit }"
                  v-model:file-list="form.pic"
                  action="http://api_devss.wanxikeji.cn/api/savePic"
                  list-type="picture-card"
                  name="img"
                  :limit="1"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handlePicSuccess"
                  :on-change="handlePicChange"
                >
                  <div class="upcover">
                    <el-icon><Plus /></el-icon>
                    <p>上传封面</p>
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">建议尺寸:1303*734px</div>
                  </template>
                </el-upload>
                <el-dialog v-model="picDialogVisible" v-if="picDialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </template>
            </el-form-item>
            <el-form-item label="收录至专栏" :label-width="formLabelWidth">
              <el-select
                v-model="form.column"
                multiple
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                placeholder="请搜索添加专栏,同—篇文章最多添加三个专栏"
              >
                <template #empty>
                  <div class="el-select__tags">
                    <span class="el-tag el-tag--gray">你还没有创建任何专栏，快去创建专栏吧~ </span>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="编辑摘要" :label-width="formLabelWidth">
              <el-input
                type="textarea"
                :rows="4"
                v-model="form.describe"
                placeholder="请输入文章摘要"
                rows="5"
                resize:none
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="morebtn">
            <el-button @click="panelVisibleValue = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">确认并发布</el-button>
          </div>
        </div>
      </div>
      <div class="toggle-btn with-margin">
        <el-button link><i class="iconfont icon-24gl-swapHorizontal3"></i></el-button>
      </div>
      <nav class="navigator with-margin">
        <el-dropdown trigger="click" placement="bottom-end">
          <span class="el-dropdown-link">
            <el-avatar :size="40" :src="squareUrl"></el-avatar>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="EditPen" command="/editor">写文章</el-dropdown-item>
              <el-dropdown-item :icon="Document">草稿</el-dropdown-item>
              <el-divider></el-divider>
              <el-dropdown-item :icon="User">我的主页</el-dropdown-item>
              <el-dropdown-item :icon="Ship">我喜欢的</el-dropdown-item>
              <el-dropdown-item :icon="Management">我的收藏集</el-dropdown-item>
              <el-dropdown-item :icon="CollectionTag">标签管理</el-dropdown-item>
              <el-divider></el-divider>
              <el-dropdown-item :icon="Tools">设置</el-dropdown-item>
              <el-dropdown-item :icon="QuestionFilled">关于</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </nav>
    </div>
  </header>
  <v-md-editor
    @upload-image="handleUploadImage"
    @change="handleChangeMd"
    v-model="form.info"
    :disabled-menus="[]"
    height="calc(100vh - 60px)"
  ></v-md-editor>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { publishApi, upImagesApi } from '@/api/publish'
import { EditPen, Document, Ship, User, Management, CollectionTag, Tools, QuestionFilled } from '@element-plus/icons-vue'
import router from '@/router'
const form = reactive({
  title: '',
  info: '',
  tags_name: [], //[[“标签一”,”标签二”]]
  article_id: 1, //帖子id(修改时必传)
  type: 1, //1帖子(默认)2沸点
  article_type: '', //分类
  pic: [], //图片(arr,json过后的内容)
  describe: '', //描述
  column: ''
})
const squareUrl = ref('https://cxjpicgo.oss-cn-chengdu.aliyuncs.com/headericon.png')
const handleUploadImage = (event, insertImage, files) => {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  console.log(files)
  let formdate = new FormData()
  formdate.append('img', files[0])
  upImagesApi(formdate).then((res) => {
    console.log(res)
    if (res.status === 200) {
      // insertImage(res.data.url)
      // 此处只做示例 {{{width="100" height="auto"}}}设置图片大小
      insertImage({
        url: 'http://api_devss.wanxikeji.cn/' + res.data.data,
        desc: res.data.msg,
        width: '300',
        height: 'auto'
      })
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
const panelVisibleValue = ref(false)
const statusText = ref('文章将自动保存至草稿箱')
/* 监听标题输入框 的状态 如果正在输入则statusText显示正在输入 如果输入完了显示保存中*/
watch(
  () => form.title,
  (val) => {
    if (val) {
      statusText.value = '正在保存...'
      setTimeout(() => {
        statusText.value = '保存成功'
      }, 1000)
    } else {
      statusText.value = '文章将自动保存至草稿箱'
    }
  }
)
/* 发布 表单 */
const lableOptions = ref([
  {
    lableId: '前端',
    lableTitle: '前端'
  },
  {
    lableId: '后端',
    lableTitle: '后端'
  },
  {
    lableId: 'JavaScript',
    lableTitle: 'JavaScript'
  },
  {
    lableId: 'GitHub',
    lableTitle: 'GitHub'
  },
  {
    lableId: '面试',
    lableTitle: '面试'
  },
  {
    lableId: '架构',
    lableTitle: '架构'
  }
])
const formLabelWidth = '82px'
const rules = ref({
  article_type: [{ required: true, message: '请选择分类', trigger: 'change' }],
  tags_name: [{ required: true, message: '请选择标签', trigger: 'change' }]
})

/* 图片上传功能 */
/* 封面预览 */
const picDialogVisible = ref(false)
const dialogImageUrl = ref('')
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  picDialogVisible.value = true
}
/* 封面移除 */
const handleRemove = (uploadFile, uploadFiles) => {
  hideUploadEdit.value = form.pic.length > 0 ? true : false
  ElMessage({
    type: 'success',
    message: '删除成功'
  })
  // console.log('删除过后的的', form.pic)
}
/* 封面上传成功处理 */
const handlePicSuccess = (response, file, files) => {
  // console.log(response, '图片上传')
  // console.log(file, '这是当前文件吗')
  file.url = 'http://api_devss.wanxikeji.cn/' + response.data
  ElMessage({
    type: 'success',
    message: '上传成功'
  })
  // console.log('成功的', form.pic)
}
/* 通过控制类名显示隐藏图框  */
const hideUploadEdit = ref(false)
const handlePicChange = () => {
  hideUploadEdit.value = form.pic.length > 0 ? true : false
}
/* 发布按钮 显示/隐藏*/
const publish = () => {
  panelVisibleValue.value = !panelVisibleValue.value
}
/* 监听编辑器改变类名 */
const mdHtmlValue = ref('')
const handleChangeMd = (text, html) => {
  console.log(text, '这是文本')
  // console.log(html, '这是html')
  // form.info = text
  // mdHtmlValue.value = html
}

const formRef = ref(null)
const onSubmit = () => {
  const { title, tags_name, type, article_type, describe } = form
  const token = localStorage.getItem('token')
  let imgs = form.pic.map((item) => {
    return item.url
  })
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await publishApi({
        token,
        title,
        info: form.info,
        tags_name,
        type,
        article_type,
        pic: imgs[0] ? imgs[0] : '',
        describe,
        tags_name
      })
      console.log(res)

      ElMessage({
        type: 'success',
        message: '发布成功'
      })
      router.push('/')
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.edito-title {
  padding: 0px 27px;
  display: flex;
  height: 60px;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  .left-box {
    padding-right: 15px;
  }
  .title-input {
    flex: 1 1 auto;
    height: 100%;
    margin: 0;
    padding: 0;
    font-size: 24px;
    font-weight: 500;
    color: #1d2129;
    border: none;
    outline: none;
  }
  .rigth-box {
    height: 32px;
    padding-left: 15px;
    display: flex;

    align-items: center;
    .status-text {
      font-size: 14px;
      white-space: nowrap;
      color: #c9cdd4;
      cursor: default;
      user-select: none;
    }
    .with-margin {
      margin-left: 8px;
      margin-right: 8px;
    }
  }
}
.publish-popup {
  position: relative;
  .panel {
    position: absolute;
    top: 52px;
    right: -30px;
    width: 560px;
    height: auto;
    background-color: #fff;
    border: 1px solid #ddd;
    z-index: 99;
    &::before {
      content: '';
      position: absolute;
      top: -8px;
      right: 50px;
      width: 15px;
      height: 15px;
      border: 1px solid #ddd;
      background-color: #fff;
      border-bottom: 1px solid #fff;
      border-right: 1px solid #fff;
      /* 旋转九十度 */
      transform: rotate(45deg);
    }
    .from-title {
      padding: 18px;
      font-size: 18px;
      border-bottom: 1px solid #ddd;
    }
    .publish-ruleForm {
      padding: 10px 18px 18px 18px;
    }
    .morebtn {
      height: 72px;

      padding: 0px 18px;
      padding-top: 18px;
      text-align: right;
      border-top: 1px solid #ddd;
    }
  }
}
.el-radio-button :deep(.el-radio-button__inner) {
  width: 88px;
  height: 28px;
  padding: 8px 20px;
  margin-right: 15px;
  margin-bottom: 10px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
}
.upcover {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  p {
    margin-top: 5px;
  }
}
.el-select {
  width: 300px;
}
.el-select__tags {
  height: 20px;
}
.el-tag.el-tag--gray {
  width: 300px;
}
:deep(.el-dialog__body) {
  text-align: center;
  overflow: hidden;
}
.hide :deep(.el-upload--picture-card) {
  display: none;
}
</style>
<style>
.el-radio-button__original-radio:checked + .el-radio-button__inner {
  border: none;
}
</style>
